package cn.fanqinghong.ymcc.mq.listener;

import cn.fanqinghong.ymcc.constants.AliPayConstants;
import cn.fanqinghong.ymcc.domain.PayOrder;
import cn.fanqinghong.ymcc.dto.NotifyDto;
import cn.fanqinghong.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * FAN
 * 2022/7/30  15:34
 */
@Component
@Slf4j
@RocketMQTransactionListener(
        txProducerGroup = AliPayConstants.ALI_ORDER_NOTIFY_GROUP //要和发送消息事务一致
 )
public class NotifyPayRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("执行本地事务");
        if (o==null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        PayOrder payOrder = (PayOrder) o;
        //查询修改订单状态之前的支付订单
        PayOrder payOrderTpm = payOrderService.selectByOrderNo(payOrder.getOrderNo());
        //如果查询到的状态不是待支付就回滚
        if (payOrderTpm.getPayStatus().intValue() !=  PayOrder.COURSE_ORDER_WAITING_TO_PAY){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //修改订单状态
        payOrderService.updateById(payOrder);
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 检查本地事务是否执行成功支付表中的订单状态是否修改成功
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("检查本地事务执行是否成功");
        try {
            byte[] payload = (byte[]) message.getPayload();
            String messageStr = new String(payload, StandardCharsets.UTF_8);
            NotifyDto notifyDto = JSONObject.parseObject(messageStr, NotifyDto.class);
            //如果
            if (notifyDto == null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            //通过订单号查询数据
            PayOrder payOrder = payOrderService.selectByOrderNo(notifyDto.getOrderNo());

            //如果查询道德支付状态为成功就提交消息给MQ
            if (payOrder.getPayStatus() == PayOrder.COURSE_ORDER_PAY_SUCCESS){
                return RocketMQLocalTransactionState.COMMIT;
            }
            //如果状态没有修改成功就回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }

    }
}
